package main

import "fmt"

func main() {
	months := [...]string{1: "January", 2: "Feb", 3: "March", 4: "April", 5: "May", 6: "June", 7: "July", 8: "August", 9: "Sept",
		10: "Oct", 11: "Nov", 12: "December"}
	Q2 := months[4:7]
	summer := months[6:9]
	fmt.Printf("%T %T\n", Q2, summer) //[]string []string
	fmt.Println(Q2)                   // ["April" "May" "June"]
	fmt.Println(summer)               // ["June" "July" "August"]
	for _, s := range summer {
		for _, q := range Q2 {
			if s == q {
				fmt.Printf("%s appears in both\n", s)
			}
		}
	}
	endlessSummer := summer[:5] // extend a slice (within capacity)
	fmt.Println(endlessSummer)  // "[June July August September October]",由原来的678变成678-9-10月
	a := [...]int{0, 1, 2, 3, 4, 5}
	reverse(a[:])
	fmt.Println(a) // "[5 4 3 2 1 0]"

	s1 := []int{}
	fmt.Printf("len = %d, cap = %d\n", len(s1), cap(s1))
	fmt.Println("s1 = ", s1)
	s1 = append(s1, 1)
	s1 = append(s1, 2)
	s1 = append(s1, 3)
	s1 = append(s1, 4)
	s1 = append(s1, 5)
	fmt.Printf("len = %d, cap = %d\n", len(s1), cap(s1)) //len = 3, cap = 4,分开一个一个加元素就会倍增,len = 5时,cap = 8
	fmt.Println("s1 = ", s1)
	data := []string{"one", "", "three"}
	fmt.Printf("%q\n", nonempty(data)) // `["one" "three"]`
	fmt.Printf("%q\n", data)           // `["one" "three" "three"]`
	s := []int{5, 6, 7, 8, 9}
	fmt.Println(remove(s, 2))  // "[5 6 8 9]"
	fmt.Println(remove1(s, 2)) //[5 6 9 9],切片是引用形式,但是这个切片的指针、长度和容量部分是直接访问
	/*
		slice并不是一个纯粹的引用类型，它实际上是一个类似下面结构体的聚合类型：

			type IntSlice struct {
				ptr *int
				len, cap int
		}

	*/
	a1 := []int{1, 2, 3}
	fmt.Println(a1, a1[:0], a1[:1])

}

// reverse reverses a slice of ints in place.
//切片是引用传递，所以不用指针就可以修改原切片
func reverse(s []int) {
	for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 {
		s[i], s[j] = s[j], s[i]
	}
}

// nonempty returns a slice holding only the non-empty strings.
// The underlying array is modified during the call.
func nonempty(strings []string) []string {
	i := 0
	for _, s := range strings {
		if s != "" {
			strings[i] = s
			i++
		}
	}
	return strings[:i]
}

func remove(slice []int, i int) []int {
	copy(slice[i:], slice[i+1:])
	return slice[:len(slice)-1]
}

func remove1(slice []int, i int) []int {
	slice[i] = slice[len(slice)-1]
	return slice[:len(slice)-1]
}
